package com.itheima.tlias84.controller;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.controller.po.UpdateDeptParam;
import com.itheima.tlias84.service.DeptService;
import com.itheima.tlias84.service.dto.SelectAllDeptDTO;
import com.itheima.tlias84.controller.po.InsertDeptParam;
import com.itheima.tlias84.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    DeptService deptService;
    /*@Resource
    private DeptService deptService = new DeptServiceImpl();*/

    @GetMapping
    public ResultUtil selectAll() {
        List<SelectAllDeptDTO> depts = deptService.selectAll();
        return ResultUtil.success(depts);
    }

    @GetMapping("/{id}")
    public ResultUtil selectOne(@PathVariable Integer id) {
        SelectAllDeptDTO dept = deptService.selectOne(id);

        if (dept != null) {
            return ResultUtil.success(dept);
        }else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PostMapping
    public ResultUtil insert(@RequestBody InsertDeptParam param) {
        log.info("读取请求体数据：{}", param.getName());

        int flag = deptService.insertDept(param);
        if (flag == 1) {
            return ResultUtil.success();
        }else {
            return ResultUtil.failure();
        }
    }

    @Log
    @DeleteMapping
    public ResultUtil deleteDeptById(@RequestParam(value = "id") Integer id) {
        int flag = deptService.deleteDeptById(id);
        if (flag == 1) {
            return ResultUtil.success();
        }else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PutMapping
    public ResultUtil updateDept(@RequestBody UpdateDeptParam deptPO) {
        int flag = deptService.updateDept(deptPO);
        if (flag == 1) {
            return ResultUtil.success();
        }else if (flag == -1) {
            return ResultUtil.failure("部门名称重复");
        }
        return ResultUtil.failure();
    }

}
